<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Pager Class
 *
 * @package		CodeIgniter
 * @subpackage	Libraries
 * @category	Pager
 * @author		vincent.wei
 */
class Pager {

	var $base_sql			= ''; 
	var $count_sql 			= '';
	var $binds				= FALSE;
	var $return_object 		= TRUE;
	
	
	var $per_page			= 10; // Max number of items you want shown per page
	var $cur_page			=  0; // The current page being viewed
	
	var $CI;
	var $db;

	/**
	 * Constructor
	 *
	 * @access	public
	 * @param	array	initialization parameters
	 */
	public function __construct($params = array())
	{
		if (count($params) > 0)
		{
			$this->initialize($params);
		}

		// Determine the current page number.
		$this->CI =& get_instance();
		
		$this->db = $this->CI->load->database('', TRUE);
		
		log_message('debug', "Pager Class Initialized");
	}

	// --------------------------------------------------------------------

	/**
	 * Initialize Preferences
	 *
	 * @access	public
	 * @param	array	initialization parameters
	 * @return	void
	 */
	function initialize($params = array())
	{
		if (count($params) > 0)
		{
			foreach ($params as $key => $val)
			{
				if (isset($this->$key))
				{
					$this->$key = $val;
				}
			}
		}
	}
	
	// --------------------------------------------------------------------
	
	/**
	 * bind pager sql
	 *
	 * @access	public
	 * @param	string	An SQL query string
	 * @param	array	An array of binding data
	 * @return	void
	 */
	function bind_sql($sql, $binds = FALSE, $return_object = TRUE)
	{
		$this->count_sql = stristr($sql, ' from ');
		
		if($this->count_sql === FALSE) {
			show_error('Your base sql incorrect.');
		}
		
		$this->base_sql = $sql;
		$this->count_sql = 'SELECT COUNT(*) as total'.$this->count_sql ;
		$this->binds = $binds;
		$this->return_object = $return_object;
		
	}

	// --------------------------------------------------------------------

	/**
	 * get total rows of the sql
	 *
	 * @access	public
	 * @return	number
	 */
	function get_total_rows()
	{
		$query = $this->db->query($this->count_sql, $this->binds, $this->return_object);
		$row = $query->row(); 
		return $row->total;
	}
	
	// --------------------------------------------------------------------

	/**
	 * get the page data
	 *
	 * @access	public
	 * @return	array
	 */
	function get_page_datas()
	{
		$sql = $this->db->_limit($this->base_sql." ", $this->per_page, $this->cur_page);
		$query = $this->db->query($sql, $this->binds, $this->return_object); 
		return $query->result() ;
	}
}
// END Pager Class

/* End of file Pager.php */
/* Location: ./application/libraries/Pager.php */